//
//  HJNetworkTools.swift
//  Swift网络工具类
//
//  Created by 韩俊 on 15/12/7.
//  Copyright © 2015年 HanJun. All rights reserved.
//

import UIKit
import AFNetworking

enum HJRequestMethod: String {
    
    case GET = "GET"
    case POST = "POST"
}

class HJNetworkTools: AFHTTPSessionManager {
    
    
    //给通过的返回闭包定义一个别名
    typealias HJNetworkToolsCallback = (response: AnyObject?,error: NSError?) -> ()
    
    static let shareTools:HJNetworkTools = {
        
        let tools = HJNetworkTools()
        
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    
    func request(method:HJRequestMethod, urlString:String, params: AnyObject?, callback: HJNetworkToolsCallback ){
        
        
        let succCallback = { (dataTask: NSURLSessionDataTask?, response: AnyObject?) -> Void in
            callback(response: response, error: nil)
        }
        
        let failureCallback = { (dataTask: NSURLSessionDataTask?, error: NSError?) -> Void in
            callback(response: nil, error: error)
        }
        
        
        if method == .GET {
            
            self.GET(urlString, parameters: params, success: succCallback, failure: failureCallback)
        }else{
            
            self.POST(urlString, parameters: params, success: succCallback, failure: failureCallback)
        }
        
        
        
    }
    
    
}

// MARK: - 首页微博数据请求
extension HJNetworkTools {
    
    func loadStatus(accessToken:String, sinceId: Int64 = 0,  maxid: Int64 = 0, callback:HJNetworkToolsCallback){
        
        let url = "https://api.weibo.com/2/statuses/friends_timeline.json"
        let params = [
            
            "access_token" : HJUserAccountViewModel.sharedAccount.accessToken!,
            "max_id": "\(maxid)",
            "since_id":"\(sinceId)"
        ]
        
        request(.GET, urlString: url, params: params, callback: callback)
    }
}

// MARK: - OAuth 登录相关的请求
extension HJNetworkTools {
    
    //加载accessToken,并且吧加载完成之后的数据回调回去
    func loadAccessToken(code:String, callback:HJNetworkToolsCallback) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = [
            
            "client_id" : WB_APPKEY,
            "client_secret" : WB_APP_SECRET,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":WB_REDIRECT_URI
        ]
        
        request(.POST, urlString: urlString, params: params, callback: callback)

    }
    
    
    func loadUserInfo(uid:String, accessToken:String, callback:HJNetworkToolsCallback) {
        
        let url = "https://api.weibo.com/2/users/show.json"
        
        let params = [
            
            "access_token":accessToken,
            "uid":uid
        ]
        
         request(.GET, urlString: url, params: params, callback: callback)

    }
    
}
